package com.passion.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.passion.utils.DatabaseUtil.getDataSource;

/**
 * @program offline-e-commerce-data-warehouse
 * @Description 执行分析工具类
 * @Author limeihua
 * @Date 2024/09/30 15:42
 * @Version 1.0
 */
@Log4j
public class ExecuteSqlUtil {
    public static String getResult(String sqlString, Map<String, String> params) {
        // 替换sql标签
        sqlString = replaceSQLTag(sqlString, params);
        DruidDataSource dataSource = getDataSource();
        DruidPooledConnection connection = null;
        JSONArray jsonArray = new JSONArray();
        try {
            connection = dataSource.getConnection();
            ResultSet resultSet = connection.prepareStatement(sqlString).executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            while (resultSet.next()) {
                JSONObject jsonObject = new JSONObject();
                for (int i = 1; i <= columnCount; i++) {
                    jsonObject.put(metaData.getColumnName(i), resultSet.getObject(i));
                }
                jsonArray.add(jsonObject);
            }
            return replaceSQLTag(jsonArray.toJSONString(), null);
        } catch (SQLException e) {
            e.printStackTrace();
            return replaceSQLTag(jsonArray.toJSONString(), null);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 替换分析sql标签
     *
     * @param sqlContent 模板sql内容
     * @param params     替换变量对应的值
     * @return 可执行分析sql
     */
    public static String replaceSQLTag(String sqlContent, Map<String, String> params) {
        if (params == null) {
            return sqlContent;
        }
        for (Map.Entry<String, String> stringStringEntry : params.entrySet()) {
            sqlContent = replacePlaceholder(sqlContent, stringStringEntry.getKey(), stringStringEntry.getValue());
        }
        log.info("替换参数为：" + params);
        log.info("即将执行分析sql：" + sqlContent);
        return sqlContent;
    }

    public static String replacePlaceholder(String sqlTemplate, String key, String value) {
        String regex = "<" + key + ">([\\s\\S]*?)</" + key + ">";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(sqlTemplate);
        String modifiedSql = matcher.replaceAll("'" + value + "'");
        return modifiedSql;
    }
}
